package com.kkb.shopcenter.filter;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.kkb.shopcenter.common.common.ResultEnum;
import com.kkb.shopcenter.common.pojo.UserInfo;
import com.kkb.shopcenter.common.utils.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 验证用户名密码正确后，生成一个token，并将token返回给客户端
 * 该类继承自UsernamePasswordAuthenticationFilter，重写了其中的2个方法
 * attemptAuthentication ：接收并解析用户凭证。
 * successfulAuthentication ：用户成功登录后，这个方法会被调用，我们在这个方法里生成token。
 * @author
 */
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

    //AuthenticationManager 为认证管理接口类，其定义了认证方法authenticate()。
    private AuthenticationManager authenticationManager;

    public JWTLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    // 接收并解析用户凭证
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException {
        try {

            //读取request请求post数据，构建UserInfo对象
            UserInfo user = new ObjectMapper().readValue(req.getInputStream(), UserInfo.class);

            //UsernamePasswordAuthenticationToken继承AbstractAuthenticationToken实现Authentication
            //所以当在页面中输入用户名和密码之后首先会进入到UsernamePasswordAuthenticationToken验证(Authentication)，
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getUserPassword(), new ArrayList<>());

            Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            return authentication;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void successfulAuthentication(HttpServletRequest request,
                                         HttpServletResponse response,
                                         FilterChain chain,
                                         Authentication authResult){

        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE,60);
        Date expireTime = calendar.getTime();
        String token = JwtUtil.createToken(authResult.getName(),now,expireTime);
        response.setStatus(ResultEnum.SUCCESS.getCode());
        response.addHeader("Authorization", "Bearer " + token);

    }




}
